package com.ryder.auth.application.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.google.common.base.Preconditions;
import com.ryder.auth.application.convert.AuthUserDTOConvert;
import com.ryder.auth.application.dto.AuthUserDTO;
import com.ryder.auth.common.entity.Result;
import com.ryder.auth.domain.entity.AuthUserBO;
import com.ryder.auth.domain.service.AuthUserDomainService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 描述: 用户管理 controller
 *
 * @author Ryder
 * @version 1.0
 * @since 1.0 // 版本号，指明从哪个版本开始
 * 更新日期: 2025/02/09
 */

@RestController
@RequestMapping("/user/")
@Slf4j
public class UserController {

    @Autowired
    private AuthUserDomainService authUserDomainService;

    /**
     * 用户注册
     */
    @RequestMapping("register")
    public Result<Boolean> register(@RequestBody AuthUserDTO authUserDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.register.dto:{}", JSON.toJSONString(authUserDto));
            }
            checkUserInfo(authUserDto);

            AuthUserBO authUserBO = AuthUserDTOConvert.INSTANCE.convertDtoToBo(authUserDto);
            return Result.ok(authUserDomainService.register(authUserBO));
        } catch (Exception e) {
            log.error("UserController.register.error: {}", e.getMessage(), e);
            return Result.fail("注册用户失败");
        }
    }

    /**
     * 更新用户信息
     */
    @RequestMapping("update")
    public Result<Boolean> update(@RequestBody AuthUserDTO authUserDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.update.dto:{}", JSON.toJSONString(authUserDto));
            }
            checkUserInfo(authUserDto);

            AuthUserBO authUserBO = AuthUserDTOConvert.INSTANCE.convertDtoToBo(authUserDto);
            return Result.ok(authUserDomainService.update(authUserBO));
        } catch (Exception e) {
            log.error("UserController.update.error: {}", e.getMessage(), e);
            return Result.fail("更新用户信息失败");
        }
    }

    /**
     * 获取用户信息
     */
    @RequestMapping("getUserInfo")
    public Result<AuthUserDTO> getUserInfo(@RequestBody AuthUserDTO authUserDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.getUserInfo.dto:{}", JSON.toJSONString(authUserDto));
            }

            Preconditions.checkArgument(StringUtils.isNotBlank(authUserDto.getUserName()), "用户唯一标识不能为空");

            AuthUserBO authUserBO = AuthUserDTOConvert.INSTANCE.convertDtoToBo(authUserDto);
            AuthUserBO resultBo = authUserDomainService.getUserInfo(authUserBO);
            return Result.ok(AuthUserDTOConvert.INSTANCE.convertBoToDto(resultBo));
        } catch (Exception e) {
            log.error("UserController.getUserInfo.error: {}", e.getMessage(), e);
            return Result.fail("获取用户信息失败");
        }
    }

    /**
     * 用户退出
     */
    @RequestMapping("logOut")
    public Result logOut(@RequestParam String userName) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.logOut.userName:{}", userName);
            }

            Preconditions.checkArgument(StringUtils.isNotBlank(userName), "用户名不能为空");
            // 当前会话注销登录
            StpUtil.logout(userName);
            return Result.ok();
        } catch (Exception e) {
            log.error("UserController.logOut.error: {}", e.getMessage(), e);
            return Result.fail("用户登出失败");
        }
    }

    /**
     * 校验用户信息
     */
    private void checkUserInfo(@RequestBody AuthUserDTO authUserDto) {
        Preconditions.checkArgument(StringUtils.isNotBlank(authUserDto.getUserName()), "用户名不能为空");
        Preconditions.checkArgument(StringUtils.isNotBlank(authUserDto.getEmail()), "邮箱不能为空");
        Preconditions.checkArgument(StringUtils.isNotBlank(authUserDto.getPassword()), "密码不能为空");
    }

    /**
     * 用户启用/禁用
     */
    @RequestMapping("changeStatus")
    public Result<Boolean> changeStatus(@RequestBody AuthUserDTO authUserDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.changeStatus.dto:{}", JSON.toJSONString(authUserDto));
            }

            Preconditions.checkNotNull(authUserDto.getStatus(), "用户状态不能为空");

            AuthUserBO authUserBO = AuthUserDTOConvert.INSTANCE.convertDtoToBo(authUserDto);
            return Result.ok(authUserDomainService.update(authUserBO));
        } catch (Exception e) {
            log.error("UserController.changeStatus.error: {}", e.getMessage(), e);
            return Result.fail("启用/禁用用户失败");
        }
    }

    /**
     * 删除用户
     */
    @RequestMapping("delete")
    public Result<Boolean> delete(@RequestBody AuthUserDTO authUserDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.delete.dto:{}", JSON.toJSONString(authUserDto));
            }

            AuthUserBO authUserBO = AuthUserDTOConvert.INSTANCE.convertDtoToBo(authUserDto);
            return Result.ok(authUserDomainService.delete(authUserBO));
        } catch (Exception e) {
            log.error("UserController.delete.error: {}", e.getMessage(), e);
            return Result.fail("删除用户信息失败");
        }
    }

    // 测试登录，浏览器访问： http://localhost:3011/user/doLogin?username=ryder&password=123456
    @RequestMapping("doLogin")
    public Result<SaTokenInfo> doLogin(@RequestParam("validCode") String validCode) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.doLogin.validCode:{}", validCode);
            }

            Preconditions.checkArgument(StringUtils.isNotBlank(validCode), "验证码不能为空");
            return Result.ok(authUserDomainService.doLogin(validCode));
        } catch (Exception e) {
            log.error("UserController.doLogin.error: {}", e.getMessage(), e);
            return Result.fail("用户登录失败");
        }
    }

    // 查询登录状态，浏览器访问： http://localhost:3011/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        System.out.println("🔍 [auth] 收到 isLogin 请求...");
        System.out.println("🔑 当前登录用户ID: " + StpUtil.getLoginIdDefaultNull());
        System.out.println("🎭 当前用户角色: " + StpUtil.getRoleList());
        System.out.println("🔐 当前用户权限: " + StpUtil.getPermissionList());
        return "当前会话是否登录：" + StpUtil.isLogin();
    }

}